var DBFactory = require('../conn/DBFactory');
var spiderVideoDao = module.exports;

var cheerio = require('cheerio');
var request = require('request');

function insertToDb(url, data, i) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            connection.query('update goods set mp4Url = ? where auctionId = ? ', [url, data[i].auctionId],
                function(err){
                    if(err){
                        console.log('更新视频地址失败');
                        connection.release();
                    } else {
                        console.log('更新视频地址成功！');
                        setTimeout(function(){
                            ++i;
                            if(i<data.length) {
                                updateVideoUrl(data, i)
                            }
                        }, 2000);
                        connection.release();
                    }
                });
        }
    });
}

function updateVideoUrl(data, i) {
    var url = 'http://www.dataoke.com/item?id=' + data[i].dtkId;
    request({url: url, method: 'GET'}, function(error, response, body) {
        if(error || !response || response.statusCode != 200 && !body) {
            console.log(error);
            console.log('页面访问失败！');
        } else {
            body = body.replace(/<img[^>]*>/igm, '');
            var $ = cheerio.load(body);
            var url = $('.goods-big-img').eq(0).children().attr('data-video');
            insertToDb(url, data, i);
        }
    });
}

function getDtkIdAndAuctionIdList(page) {
    var url = 'http://www.dataoke.com/qlist/?px=zh&video=video&page=' + page;
    request({url: url, method: 'GET'}, function(error, response, body) {
        if(error || !response || response.statusCode != 200 && !body) {
            console.log(error);
            console.log('页面访问失败！');
        } else {
            body = body.replace(/<img[^>]*>/igm, '');
            var $ = cheerio.load(body);
            var goods = $('.goods-item');
            var data = [];
            for(var i=0; i<goods.length; i++) {
                var auctionId = goods.eq(i).attr('data_goodsid');
                var dtkId = goods.eq(i).attr('id').split('_')[1];
                var g = {};
                g.auctionId = auctionId;
                g.dtkId = dtkId;
                data.push(g);
            }
            updateVideoUrl(data, 0);
        }
    });
}

spiderVideoDao.spiderVideo = function(data, cb) {
    if(!data) return cb(new Error(500));
    getDtkIdAndAuctionIdList(data.page);
    cb(null);
}

function insertToDb2(url, data, i, page) {
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            connection.query('update goods set mp4Url = ? where auctionId = ? ', [url, data[i].auctionId],
                function(err){
                    if(err){
                        console.log('更新视频地址失败');
                        connection.release();
                    } else {
                        console.log('更新视频地址成功！');
                        setTimeout(function(){
                            ++i;
                            if(i<data.length) {
                                updateVideoUrl2(data, i, page);
                            } else {
                                ++page;
                                getDtkIdAndAuctionIdList2(page);
                                console.log('第' + page);
                            }
                        }, 2000);
                        connection.release();
                    }
                });
        }
    });
}

function updateVideoUrl2(data, i, page) {
    var url = 'http://www.dataoke.com/item?id=' + data[i].dtkId;
    request({url: url, method: 'GET'}, function(error, response, body) {
        if(error || !response || response.statusCode != 200 && !body) {
            console.log(error);
            console.log('页面访问失败！');
        } else {
            body = body.replace(/<img[^>]*>/igm, '');
            var $ = cheerio.load(body);
            var url = $('.goods-big-img').eq(0).children().attr('data-video');
            insertToDb2(url, data, i, page);
        }
    });
}

function getDtkIdAndAuctionIdList2(page) {
    var url = 'http://www.dataoke.com/qlist/?px=zh&video=video&page=' + page;
    request({url: url, method: 'GET'}, function(error, response, body) {
        if(error || !response || response.statusCode != 200 && !body) {
            console.log(error);
            console.log('页面访问失败！');
        } else {
            body = body.replace(/<img[^>]*>/igm, '');
            var $ = cheerio.load(body);
            var goods = $('.goods-item');
            var data = [];
            for(var i=0; i<goods.length; i++) {
                var auctionId = goods.eq(i).attr('data_goodsid');
                var dtkId = goods.eq(i).attr('id').split('_')[1];
                var g = {};
                g.auctionId = auctionId;
                g.dtkId = dtkId;
                data.push(g);
            }
            getNoNeedToUpdateAuctionId(data, function(err, d) {
                if(err) {
                    console.log(err);
                    console.log('获取需要更新的auctionId失败！');
                } else {
                    if(d.length > 0) {
                        updateVideoUrl2(d, 0, page);
                    } else {
                        return;
                    }
                }
            });
        }
    });
}

function getNoNeedToUpdateAuctionId(data, cb) {
    var auctionIds = [];
    data.forEach(function(g) {
        auctionIds.push(g.auctionId);
    });
    var sql = 'select auctionId from goods where auctionId in ( ? ) and mp4Url is null ';
    DBFactory.getConnection(function(error, connection){
        if(error) {
            console.log(error);
            return;
        } else {
            connection.query(sql, [auctionIds],
                function(err, result){
                    if(err){
                        console.log('getNoNeedToUpdateAuctionId err: ' + err);
                        connection.release();
                    } else {
                        if(result.length > 0) {
                            var d = [];
                            data.forEach(function(g) {
                                for(var i=0; i<result.length; i++ ) {
                                    if(result[i].auctionId == g.auctionId) {
                                        d.push(g);
                                    }
                                }
                            });
                            cb(null, d);
                        } else {
                            cb(null, []);
                        }
                    }
                });
        }
    });
}

spiderVideoDao.autoSpiderVideo = function(data, cb) {
    if(!data) return cb(new Error(500));
    getDtkIdAndAuctionIdList2(data.page);
    cb(null);
}